/*
 * 文件名：DeviceSureController.java
 * 版权：Copyright by www.infopub.top
 * 描述：
 * 修改人：wangw
 * 修改时间：2020年2月19日
 * 跟踪单号：
 * 修改单号：
 * 修改内容：
 */

package top.infopub.mgr.bpa.web;


import com.github.pagehelper.Page;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.servlet.ModelAndView;
import top.infopub.mgr.bpa.domain.DeviceSureDomain;
import top.infopub.mgr.bpa.service.DeviceCotService;
import top.infopub.mgr.bpa.service.DeviceSureDetailService;
import top.infopub.mgr.bpa.service.DeviceSureService;
import top.infopub.mgr.bpa.vo.DeviceSureVo;
import top.infopub.mgr.common.page.ParamPage;
import top.infopub.mgr.common.vo.ErrorCodeEnum;
import top.infopub.mgr.common.vo.RspVo;
import top.infopub.mgr.flow.web.GenericFlowController;
import top.infopub.mgr.hr.service.OrgInfoService;
import top.infopub.mgr.hr.service.StaffInfoService;
import top.infopub.mgr.util.DateUtils;
import top.infopub.mgr.util.FileHelper;
import top.infopub.mgr.util.LogUtil;
import top.infopub.mgr.util.LogUtil.AcctionType;
import top.infopub.mgr.util.LogUtil.LogModelType;
import top.infopub.model.bpa.DeviceSureAtt;
import top.infopub.model.bpa.DeviceSureDetail;
import top.infopub.model.hr.OrgInfo;
import top.infopub.model.hr.StaffInfo;
import top.infopub.security.util.SessionUserUtils;
import top.infopub.security.vo.AuthorizationVO;
import top.infopub.tdp.sys.service.CodeGeneratorConfigService;
import top.infopub.util.IdFactory;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.math.BigDecimal;
import java.text.ParseException;
import java.util.*;


/**
 * @author wangw
 * @version 2020年2月21日
 * @see DeviceSureController
 * @since
 */
@Controller
@RequestMapping("/deviceSure")
public class DeviceSureController extends GenericFlowController {

    @Autowired
    private DeviceSureService deviceSureService;

    @Autowired
    private DeviceSureDetailService deviceSureDetailService;

    @Autowired
    private DeviceCotService deviceCotService;

    @Autowired
    private StaffInfoService staffInfoService;

    @Autowired
    private CodeGeneratorConfigService codeGeneratorConfigService;

    @Autowired
    private OrgInfoService orgInfoService;

    /**
     * 跳转列表页
     *
     * @return
     */
    @RequestMapping("/list")
    public String list(HttpServletRequest request) {
        return "bpa/lay-deviceSure-list";
    }

    /**
     * 设备合同列表数据
     *
     * @return
     */
    @RequestMapping("/queryDataByCondition")
    @ResponseBody
    public RspVo<DeviceSureDomain> queryDataByCondition(DeviceSureVo deviceSureVo,
                                                        ParamPage paramPage,
                                                        String monthStartDateStr,
                                                        String monthEndDateStr) {
        Page<DeviceSureDomain> page = new Page<DeviceSureDomain>();
        page.setPageNum(paramPage.getPage());
        page.setPageSize(paramPage.getLimit());
        //查询时，结束日期增加一天
        if (deviceSureVo.getEndDate() != null) {
            deviceSureVo.setEndDate(DateUtils.addDays(deviceSureVo.getEndDate(), 1));
        }
        //查询时，创效月份开始日期
        if (StringUtils.isNotEmpty(monthStartDateStr)) {
            deviceSureVo.setMonthStartDate(DateUtils.convertToDate(monthStartDateStr + "-01"));
        }
        //查询时，创效月份结束日期增加一天
        if (StringUtils.isNotEmpty(monthEndDateStr)) {
            deviceSureVo.setMonthEndDate(DateUtils.getMonthEnd(DateUtils.convertToDate(
                monthEndDateStr, "yyyy-MM")));
        }
        page = deviceSureService.selectPageByDomainWhere(page, deviceSureVo);
        return RspVo.getSuccessResponse(page.getTotal(), page.getResult());
    }

    /**
     * 设备合同-我审批的列表数据
     *
     * @return
     */
    @RequestMapping("/queryMyCheckDataByCondition")
    @ResponseBody
    public RspVo<DeviceSureDomain> queryMyCheckDataByCondition(DeviceSureVo deviceSureVo,
                                                               ParamPage paramPage,
                                                               String monthStartDateStr,
                                                               String monthEndDateStr) {
        Page<DeviceSureDomain> page = new Page<DeviceSureDomain>();
        page.setPageNum(paramPage.getPage());
        page.setPageSize(paramPage.getLimit());
        //查询时，结束日期增加一天
        if (deviceSureVo.getEndDate() != null) {
            deviceSureVo.setEndDate(DateUtils.addDays(deviceSureVo.getEndDate(), 1));
        }
        //查询时，创效月份开始日期
        if (StringUtils.isNotEmpty(monthStartDateStr)) {
            deviceSureVo.setMonthStartDate(DateUtils.convertToDate(monthStartDateStr + "-01"));
        }
        //查询时，创效月份结束日期增加一天
        if (StringUtils.isNotEmpty(monthEndDateStr)) {
            deviceSureVo.setMonthEndDate(DateUtils.getMonthEnd(DateUtils.convertToDate(
                monthEndDateStr, "yyyy-MM")));
        }
        deviceSureVo.setAddBy(SessionUserUtils.getSessionUserId());
        page = deviceSureService.selectMyCheckByDomainWhere(page, deviceSureVo);
        return RspVo.getSuccessResponse(page.getTotal(), page.getResult());
    }

//    /**
//     * 设备合同-新增
//     *
//     * @return
//     */
//    @RequestMapping("/add")
//    public String add(HttpServletRequest request) {
//        //查询可公司年度预算的公司年度预算记录
//        AuthorizationVO authorizationVO = SessionUserUtils.getSessionAttributeForUserDtl();
//        StaffInfo staffInfo = staffInfoService.selectByPrimaryKey(authorizationVO.getHrStaffId());
//        request.setAttribute("staffName", staffInfo.getStaffName());
//        //查询所有设备合同原合同
//        List<DeviceCot> deviceCots = deviceCotService.selectByDeviceCots();
//        request.setAttribute("deviceCots", deviceCots);
//        return "bpa/lay-deviceSure-add";
//    }

//    /**
//     * 根据id查询设备合同记录
//     * @param id
//     * @return
//     */
//    @RequestMapping("/getDeviceCotById")
//    @ResponseBody
//    public Map<String, Object> getDeviceCotById(String id) {
//        boolean flag = true;
//        Map<String, Object> map = new HashMap<String, Object>();
//        try {
//            DeviceCotVo deviceCotVo = new DeviceCotVo();
//            /**
//             * 查询最新的设备合同记录
//             */
//            Map<String, Object> mapWhere = new HashMap<String, Object>();
//            mapWhere.put("refId", id);
//            mapWhere.put("orderCondition", "ADD_TIME desc");
//            List<DeviceCot> deviceCots = deviceCotService.selectByMapWhere(mapWhere);
//            if (CollectionUtils.isNotEmpty(deviceCots)) {
//                deviceCotVo = deviceCotService.queryById(deviceCots.get(0).getId());
//            }
//            else {
//                deviceCotVo = deviceCotService.queryById(id);
//            }
//            if (deviceCotVo != null) {
//                map.put("deviceCotVo", deviceCotVo);
//            }
//            else {
//                flag = false;
//            }
//        }
//        catch (Exception e) {
//            log.error("查询设备合同记录异常", e);
//            flag = false;
//        }
//        map.put("flag", flag);
//        return map;
//    }

    /**
     * 根据分部分项名称和设备合同id查询月累金额
     * @param id
     * @return
     */
    @RequestMapping("/getAddupAmountBySubNameAndRefId")
    @ResponseBody
    public Map<String, Object> getAddupAmountBySubNameAndRefId(String subName, String refId) {
        boolean flag = true;
        Map<String, Object> map = new HashMap<String, Object>();
        if (StringUtils.isBlank(subName) || StringUtils.isBlank(refId)) {
            flag = false;
        }
        else {
            try {
                BigDecimal addupAmountTotal = deviceSureDetailService.selectAddupAmountBySubNameAndRefId(
                    subName, refId);
                map.put("addupAmountTotal", addupAmountTotal);
            }
            catch (Exception e) {
                log.error("查询创效计划记录异常", e);
                flag = false;
            }
        }
        map.put("flag", flag);
        return map;
    }

    /**
     * 设备合同-新增
     * @throws ParseException 
     */
    @SuppressWarnings("rawtypes")
    @RequestMapping("/save")
    @ResponseBody
    public RspVo save(HttpServletRequest request, DeviceSureVo deviceSure, String deviceCotId,
                      String sumTotal, String sureMonthStr)
        throws ParseException {
        String[] fileAtt11 = request.getParameterValues("fileAtt11");
        String[] fileAtt12 = request.getParameterValues("fileAtt12");
        String[] fileAtt4 = request.getParameterValues("fileAtt4");

        AuthorizationVO vo = SessionUserUtils.getSessionAttributeForUserDtl();
        String id = IdFactory.getUUIDUpper();
        deviceSure.setId(id);
        deviceSure.setHrStaffApplyId(vo.getHrStaffId());
        deviceSure.setHrOrgId(String.valueOf(SessionUserUtils.getSessionAttribute("bindOrgId")));
        deviceSure.setHrDeptId(String.valueOf(SessionUserUtils.getSessionAttribute("bindDeptId")));
        StaffInfo staffInfo = staffInfoService.selectByPrimaryKey(vo.getHrStaffId());
        deviceSure.setStaffName(staffInfo.getStaffName());
        deviceSure.setHrStaffApplyId(vo.getHrStaffId());
        deviceSure.setAddBy(vo.getId());
        deviceSure.setAddTime(top.infopub.mgr.util.DateUtils.getCurrentDateTime());
        String codes = codeGeneratorConfigService.generatorCode("bpa_device_sure");
        deviceSure.setCodes(codes);
        deviceSure.setProcessId(IdFactory.getUUIDUpper());
        deviceSure.setRefId(deviceCotId);
        deviceSure.setCotSumPrice(new BigDecimal(sumTotal));
        Date month = DateUtils.parseDate(sureMonthStr, "yyyy-MM");
        deviceSure.setSureMonth(month);
        //设置审批状态
        deviceSure.setProcessStatus("1");
        deviceSure.setUptBy(vo.getId());
        deviceSure.setUptTime(top.infopub.mgr.util.DateUtils.getCurrentDateTime());

        //子表数据处理
        List<DeviceSureDetail> deviceSureDetails = new ArrayList<DeviceSureDetail>();
        for (DeviceSureDetail deviceSureDetail : deviceSure.getDeviceSureDetails()) {
            String detailId = IdFactory.getUUIDUpper();
            deviceSureDetail.setId(detailId);
            deviceSureDetail.setDeviceSureId(id);
            deviceSureDetail.setAddBy(vo.getId());
            deviceSureDetail.setAddTime(top.infopub.mgr.util.DateUtils.getCurrentDateTime());
            deviceSureDetails.add(deviceSureDetail);
        }

        List<DeviceSureAtt> deviceSureAtts = new ArrayList<DeviceSureAtt>();
        if (fileAtt11 != null) {
            for (String file : fileAtt11) {
                DeviceSureAtt deviceSureAtt = createFileAtt(vo, id, file);
                deviceSureAtts.add(deviceSureAtt);
            }
        }
        if (fileAtt12 != null) {
            for (String file : fileAtt12) {
                DeviceSureAtt deviceSureAtt = createFileAtt(vo, id, file);
                deviceSureAtts.add(deviceSureAtt);
            }
        }
        if (fileAtt4 != null) {
            for (String file : fileAtt4) {
                DeviceSureAtt deviceSureAtt = createFileAtt(vo, id, file);
                deviceSureAtts.add(deviceSureAtt);
            }
        }
        deviceSureService.save(deviceSure, deviceSureDetails, deviceSureAtts);
        LogUtil.bizLog(LogUtil.LogModelType.PROJECT, LogUtil.AcctionType.ADD,
            "商务管理 -确权支付-新增设备产值确权：项目名=" + deviceSure.getProName(), null);
        return RspVo.getSuccessResponse();
    }

    /**
     * 根据id查询设备合同详细  > 注意：方法命名必须为：toDealOrDetail
     *
     * @param id 投建项目id
     * @return
     * @see
     */
    @RequestMapping("/toDealOrDetail")
    public ModelAndView queryById(HttpServletRequest request, String id, String processDealWith) {
        Map<String, Object> map = new HashMap<String, Object>();
        DeviceSureVo deviceSure = deviceSureService.queryById(id);
        OrgInfo orgInfo = new OrgInfo();
        orgInfo.setProjectCode(deviceSure.getProCode());
        orgInfo.setState(1);
        List<OrgInfo> orgInfos = orgInfoService.selectByEntityWhere(orgInfo);
        if (orgInfos.size() > 0) {
            deviceSure.setOrgProName(orgInfos.get(0).getCompName());
            deviceSure.setHrOrgProId(orgInfos.get(0).getId());
            OrgInfo parentOrgInfo = new OrgInfo();
            parentOrgInfo.setId(orgInfos.get(0).getParentId());
            parentOrgInfo.setState(1);
            List<OrgInfo> parentOInfos = orgInfoService.selectByEntityWhere(parentOrgInfo);
            if (parentOInfos.size() > 0) {
                deviceSure.setOrgAreName(parentOInfos.get(0).getCompName());
                deviceSure.setHrOrgAreaId(parentOInfos.get(0).getId());
            }
        }
        map.put("deviceSure", deviceSure);
        // 审批flag
        request.setAttribute("processDealWith", processDealWith);
        // 审批data
        processData(request, deviceSure.getProcessId());
        return new ModelAndView("bpa/lay-deviceSure-detail", map);
    }

    private DeviceSureAtt createFileAtt(AuthorizationVO vo, String deviceSureId, String file) {
        //附件信息数组
        String[] fileAttStr = file.split("\\|");
        DeviceSureAtt fileAtt = new DeviceSureAtt();
        if (StringUtils.isNotEmpty(fileAttStr[2])) {
            fileAtt.setId(fileAttStr[2]);
        }
        else {
            fileAtt.setId(IdFactory.getUUIDSerialNumber());
        }
        fileAtt.setTypes(fileAttStr[0]);
        fileAtt.setDeviceSureId(deviceSureId);//项目id
        String fileName = fileAttStr[1].substring(0, fileAttStr[1].lastIndexOf("."));
        String suffix = fileAttStr[1].substring(fileAttStr[1].lastIndexOf("."),
            fileAttStr[1].length()).toLowerCase();//后缀转小写
        fileAtt.setFileName(fileName);//文件名
        fileAtt.setFileSuffix(suffix);//文件后缀
        fileAtt.setFilePath(fileAttStr[3]);//文件保存路径
        fileAtt.setAddBy(vo.getId());//添加人
        fileAtt.setAddTime(top.infopub.mgr.util.DateUtils.getCurrentDateTime());//添加时间
        return fileAtt;
    }

    /**
     * 上传附件
     * @param request
     * @param response
     * @return 
     * @throws IOException 
     * @see
     */
    @SuppressWarnings("rawtypes")
    @RequestMapping("/uploadAtt")
    public @ResponseBody RspVo uploadAtt(HttpServletRequest request)
        throws IOException {
        List<String> returnFileStrList = new ArrayList<>();
        MultipartHttpServletRequest multipartHttpServletRequest = (MultipartHttpServletRequest)request;
        Map<String, MultipartFile> map = multipartHttpServletRequest.getFileMap();
        if (map != null) {
            for (String name : map.keySet()) {
                MultipartFile file = map.get(name);
                if (file == null) {
                    return ErrorCodeEnum.ERROR_COMMON_PARAM.getRspVo("上传文件不能为空");
                }
                //资料类型
                String types = request.getParameter("types");
                if (StringUtils.isEmpty(types)) {
                    return ErrorCodeEnum.ERROR_COMMON_PARAM.getRspVo("缺少参数");
                }
                // 上传文件
                String fileId = IdFactory.getUUIDSerialNumber();
                // 服务器资源路径
                String serverPath = "deviceSureAtt";
                String filePath = FileHelper.upload(file, serverPath);
                returnFileStrList.add(types + "|" + file.getOriginalFilename().trim() + "|"
                                      + fileId + "|" + filePath);
                LogUtil.bizLog(LogModelType.PROJECT, AcctionType.ADD, "上传附件-文件名:" + filePath
                                                                      + "，文件路径:" + filePath, null);
            }
        }
        return RspVo.getSuccessResponse(returnFileStrList);
    }

    /**
     * 设备合同确权-复制单据
     * @return
     */
    @RequestMapping("/toCopy")
    public String toCopy(HttpServletRequest request) {
        String id = request.getParameter("id");
        DeviceSureVo deviceSure = deviceSureService.queryById(id);
        request.setAttribute("deviceSure", deviceSure);
        return "bpa/lay-deviceSure-copy";
    }

}
